import * as fs from 'fs';
import * as path from 'path';
import { homedir, platform } from 'os';
import type {Config} from "../../common/types";


function getConfigFilePath(): string {
    const isWindows = platform() === 'win32';
    if (isWindows) {
        return path.join('C:\\', 'config','transformer_back_v2', 'client.json');
    } else {
        // 对于 Unix-like 系统，使用用户主目录
        return path.join(homedir(), 'config', 'transformer_back_v2','client.json');
    }
}

function readConfigFileSync<T>(): T {
    try {
        const configPath = getConfigFilePath();
        const data = fs.readFileSync(configPath, 'utf8');
        return JSON.parse(data) as T;
    } catch (err) {
        if (err.code === 'ENOENT') {
            console.error(`配置文件不存在: ${getConfigFilePath()}`);
        } else if (err instanceof SyntaxError) {
            console.error('JSON 解析错误:', err.message);
        } else {
            console.error('读取配置文件失败:', err);
        }
        throw err; // 重新抛出错误，以便调用者可以处理
    }
}

export const loadConfig:()=>Config = ()=>{
    try {
        return readConfigFileSync<Config>();
    }catch(err){
        console.log(err);
        console.log("use default config");
        return {
            serviceName:"",
            backend:"127.0.0.1:9123",
        }
    }
}
